<template>
  <!-- 这里可以添加一些用于显示解析结果的 HTML 结构 -->
  <div v-if="lyrics.length > 0" class="krc" ref="krcRef">
    <div v-for="(line) in lyrics" :key="line.i" class="lyric-line">
      <span v-for="(char, charIndex) in line.chars" :key="charIndex"
        :style="{ backgroundImage: getGradientStyle(line.startTime, line.startTime + line.lineDuration, char.timeOffset, char.duration) }">
        <!-- 使用特效字体和渐变背景 -->
        {{ char.text }}
      </span>
    </div>
  </div>
  <p v-else>暂无歌词信息</p>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';

// 接收外部传入的 KRC 歌词文件内容和当前播放时间
const props = defineProps({
  krcContent: {
    type: String,
    required: true
  },
  currentTime: {
    type: Number,
    default: 0
  },
  id: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['changeImageUrl']);

// 存储解析后的歌词
const lyrics = ref([]);
// 引用歌词容器
const krcRef = ref(null);

// 解析 KRC 歌词文件的函数
const parseKrc = (krcContent) => {
  if (!krcContent) return [];
  const lines = krcContent.split('\n');
  const result = [];

  for (const line of lines) {
    // 匹配歌词行，格式如：[开始时间,持续时间]<字开始时间,字持续时间,0>字
    const lineRegex = /\[(\d+),(\d+)\](.*)/;
    const lineMatch = line.match(lineRegex);
    if (lineMatch) {
      const startTime = parseInt(lineMatch[1]);
      const lineDuration = parseInt(lineMatch[2]);
      const lineText = lineMatch[3];

      const charRegex = /<(\d+),(\d+),\d+>(.)/g;
      const chars = [];
      let charMatch;
      while ((charMatch = charRegex.exec(lineText)) !== null) {
        const timeOffset = parseInt(charMatch[1]);
        const duration = parseInt(charMatch[2]);
        const text = charMatch[3];
        chars.push({ timeOffset, duration, text });
      }

      result.push({ startTime, lineDuration, chars });
    }
  }

  return result;
};

// 计算每个字的渐变样式
const getGradientStyle = (lineStartTime, lineEndTime, charTimeOffset, charDuration) => {
  const currentTimeInMs = props.currentTime * 1000;
  const charStartTime = lineStartTime + charTimeOffset;
  const charEndTime = charStartTime + charDuration;
  if (currentTimeInMs < charStartTime) {
    return 'linear-gradient(to right, #87CEFA, #87CEFA)';
  } else if (currentTimeInMs >= charEndTime) {
    return 'linear-gradient(to right, #ffeb3b, #ffeb3b)';
  } else {
    const progress = (currentTimeInMs - charStartTime) / charDuration;
    return `linear-gradient(to right, #ffeb3b ${progress * 100}%, #87CEFA ${progress * 100}%)`;
  }
};

const lyricsGroup = (line, index) => {
  line['i'] = index;
  return line;
}

const index = ref(-1)
// 筛选出可见的歌词行
const getVisibleLyrics = () => {
  const currentTimeInMs = props.currentTime * 1000;
  // 找到当前正在播放的歌词行索引
  let currentIndex = -1;
  for (let i = 0; i < lyrics.value.length; i++) {
    const line = lyrics.value[i];
    if (line.startTime <= currentTimeInMs && line.startTime + line.lineDuration > currentTimeInMs) {
      currentIndex = i;
      break;
    }
  }

  if (krcRef.value && currentIndex != index.value) {
    index.value = currentIndex;
    let txt = lyrics.value[currentIndex]?.chars?.map(o => o.text)?.join("");
    if (txt) {
      emit('changeImageUrl', txt + '.png')
      // 预加载一张图片
      if (lyrics.value.length > currentIndex + 1) {
        txt = lyrics.value[currentIndex + 1]?.chars?.map(o => o.text)?.join("");
        const img = new Image();
        img.src = '/song/' + props.id + '/' + txt + '.png';
      }
      // 预加载两张图片
      if (lyrics.value.length > currentIndex + 2) {
        txt = lyrics.value[currentIndex + 2]?.chars?.map(o => o.text)?.join("");
        const img = new Image();
        img.src = '/song/' + props.id + '/' + txt + '.png';
      }
    }
    const lineElement = krcRef.value.querySelector(`.lyric-line:nth-child(${currentIndex + 1})`);
    if (lineElement) {
      const containerHeight = krcRef.value.offsetHeight;
      const lineTop = lineElement.offsetTop;
      const lineHeight = lineElement.offsetHeight;
      const targetScrollTop = lineTop - (containerHeight / 2) + (lineHeight / 2);
      const currentScrollTop = krcRef.value.scrollTop;
      const distance = targetScrollTop - currentScrollTop;
      const duration = 500; // 动画持续时间，单位为毫秒
      const startTime = performance.now();

      const scrollAnimation = (timestamp) => {
        const elapsed = timestamp - startTime;
        if (elapsed < duration) {
          const progress = elapsed / duration;
          const newScrollTop = currentScrollTop + distance * progress;
          krcRef.value.scrollTop = newScrollTop;
          requestAnimationFrame(scrollAnimation);
        } else {
          krcRef.value.scrollTop = targetScrollTop;
        }
      };
      requestAnimationFrame(scrollAnimation);
    }
  }
};

// 当传入的 KRC 内容或当前时间变化时，重新解析歌词并更新可见歌词行
watch(() => props.krcContent, () => {
  lyrics.value = parseKrc(props.krcContent);
}, { immediate: true });
watch(() => props.currentTime, () => {
  getVisibleLyrics();
}, { immediate: true });
</script>

<style scoped>
/* 可以在这里添加样式 */
.krc {
  position: absolute;
  font-weight: bold;
  font-size: var(--td-krc-font-size);
  height: var(--td-krc-h);
  width: 80%;
  overflow: hidden;
  bottom: 2rem;
  left: 10%;
  text-shadow: 5px 5px 6px rgba(0, 0, 0, .3);
}

.lyric-line {
  line-height: 1.5;
  margin-bottom: 10px;
  /* 添加位置过渡动画 */
  transition: transform 2s ease;
}

/* 定义过渡动画样式 */
.lyric-transition-enter-active {
  /* 进入动画，从底部向上滚动 */
  animation: slideIn 2s ease;
}

.lyric-transition-leave-active {
  /* 离开动画，从顶部向上滚动 */
  animation: slideOut 2s ease;
}

/* 定义进入动画 */
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(100%);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 定义离开动画 */
@keyframes slideOut {
  from {
    opacity: 1;
    transform: translateY(0);
  }

  to {
    opacity: 0;
    transform: translateY(-100%);
  }
}

/* 让文字颜色根据背景渐变显示 */
span {
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
</style>